<?php
session_start();
// 验证管理员权限
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 版本号排序函数（内置，不依赖外部文件）
function getVersionNumberArray($version) {
    $numStr = ltrim($version, 'V');
    return array_map('intval', explode('.', $numStr));
}
function compareVersions($a, $b) {
    $aArr = getVersionNumberArray($a['version_code']);
    $bArr = getVersionNumberArray($b['version_code']);
    $maxLen = max(count($aArr), count($bArr));
    for ($i = 0; $i < $maxLen; $i++) {
        $aVal = $aArr[$i] ?? 0;
        $bVal = $bArr[$i] ?? 0;
        if ($aVal > $bVal) return -1;
        if ($aVal < $bVal) return 1;
    }
    return 0;
}

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$versions = [];
$error = '';
$success = '';
$currentVersion = []; // 编辑时的版本数据

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // 1. 获取所有版本记录并排序
    $stmt = $pdo->query("SELECT * FROM version_detail");
    $versions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    usort($versions, 'compareVersions');

    // 2. 处理表单提交（新增/编辑）
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $versionCode = trim($_POST['version_code'] ?? '');
        $title = trim($_POST['title'] ?? '');
        $type = $_POST['type'] ?? '';
        $content = trim($_POST['content'] ?? '');
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

        // 自动补全V前缀
        if (strpos($versionCode, 'V') !== 0) {
            $versionCode = 'V' . $versionCode;
        }

        // 验证必填项
        if (empty($versionCode) || empty($title) || empty($type) || empty($content)) {
            $error = "所有字段均为必填";
        } else {
            try {
                if ($id > 0) {
                    // 编辑操作
                    $stmt = $pdo->prepare("UPDATE version_detail SET 
                        version_code = :version_code, 
                        title = :title, 
                        type = :type, 
                        content = :content 
                        WHERE id = :id");
                    $stmt->execute([
                        ':version_code' => $versionCode,
                        ':title' => $title,
                        ':type' => $type,
                        ':content' => $content,
                        ':id' => $id
                    ]);
                    $success = "版本记录更新成功";
                } else {
                    // 新增操作
                    $stmt = $pdo->prepare("INSERT INTO version_detail (
                        version_code, title, type, content, create_time
                    ) VALUES (:version_code, :title, :type, :content, NOW())");
                    $stmt->execute([
                        ':version_code' => $versionCode,
                        ':title' => $title,
                        ':type' => $type,
                        ':content' => $content
                    ]);
                    $success = "版本记录添加成功";
                }
                header('Location: version.php?success=' . urlencode($success));
                exit;
            } catch (PDOException $e) {
                $error = "操作失败：" . $e->getMessage();
            }
        }
    }

    // 3. 编辑时获取版本数据（用于表单填充）
    if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
        $id = (int)$_GET['edit'];
        $stmt = $pdo->prepare("SELECT * FROM version_detail WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $currentVersion = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    }

    // 4. 删除版本
    if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
        $id = (int)$_GET['delete'];
        $stmt = $pdo->prepare("DELETE FROM version_detail WHERE id = :id");
        $stmt->execute([':id' => $id]);
        header('Location: version.php?success=版本记录已删除');
        exit;
    }

} catch (PDOException $e) {
    $error = "数据库连接失败：" . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>版本管理 - 知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/common.css">
    <style>
        /* 表单默认隐藏，通过JS控制显示 */
        .form-card.hidden {
            display: none;
        }
        .form-card {
            margin-bottom: 1.5rem;
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏 -->
        <aside class="admin-sidebar">
            <div class="sidebar-logo">
                <i class="fas fa-cogs"></i>
                <span>知识库管理</span>
            </div>
            <ul class="nav-list">
                <li class="nav-item"><a href="index.php" class="nav-link"><i class="fas fa-home"></i><span>管理首页</span></a></li>
                <li class="nav-item"><a href="article.php" class="nav-link"><i class="fas fa-file-alt"></i><span>文章管理</span></a></li>
                <li class="nav-item"><a href="category.php" class="nav-link"><i class="fas fa-folder"></i><span>分类管理</span></a></li>
                <li class="nav-item"><a href="version.php" class="nav-link active"><i class="fas fa-sync-alt"></i><span>版本管理</span></a></li>
                <li class="nav-item"><a href="user.php" class="nav-link"><i class="fas fa-users"></i><span>用户管理</span></a></li>
                <li class="nav-item"><a href="logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></a></li>
            </ul>
        </aside>

        <!-- 主内容区 -->
        <main class="admin-content">
            <div class="content-wrapper">
                <!-- 页面标题和新增按钮 -->
                <div class="page-header">
                    <h1 class="page-title">版本管理</h1>
                    <!-- 新增按钮：点击显示表单 -->
                    <button class="btn btn-primary" onclick="showForm('新增版本', 0)">
                        <i class="fas fa-plus"></i> 新增版本
                    </button>
                </div>

                <!-- 提示信息 -->
                <?php if (isset($_GET['success'])): ?>
                    <div class="message message-success"><i class="fas fa-check-circle"></i><?php echo htmlspecialchars($_GET['success']); ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="message message-error"><i class="fas fa-exclamation-circle"></i><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>

                <!-- 版本表单（默认隐藏） -->
                <div class="form-card hidden" id="versionFormCard">
                    <h3 id="formTitle">新增版本</h3>
                    <form method="POST" action="" id="versionForm">
                        <input type="hidden" name="id" id="formId" value="0"> <!-- 编辑时填充ID -->
                        
                        <div class="form-group">
                            <label class="form-label" for="version_code">版本号 <span style="color: #EF4444;">*</span></label>
                            <input type="text" id="version_code" name="version_code" class="form-control" 
                                value="V" placeholder="如V1.2.2">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="title">版本标题 <span style="color: #EF4444;">*</span></label>
                            <input type="text" id="title" name="title" class="form-control" 
                                placeholder="请输入版本标题">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="type">更新类型 <span style="color: #EF4444;">*</span></label>
                            <select id="type" name="type" class="form-control">
                                <option value="功能">功能</option>
                                <option value="优化">优化</option>
                                <option value="修复">修复</option>
                                <option value="重构">重构</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="content">更新详情 <span style="color: #EF4444;">*</span></label>
                            <textarea id="content" name="content" class="form-control" rows="6" 
                                placeholder="请输入更新详情，每行一条"></textarea>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">保存</button>
                            <button type="button" class="btn btn-outline" onclick="hideForm()">取消</button>
                        </div>
                    </form>
                </div>

                <!-- 版本记录列表（始终显示） -->
                <div class="form-card">
                    <h3>版本记录列表</h3>
                    <div style="overflow-x: auto; margin-top: 1rem;">
                        <table style="width:100%; border-collapse:collapse;">
                            <thead>
                                <tr style="background:#F1F5F9; border-bottom:1px solid #E2E8F0;">
                                    <th style="padding:0.75rem; text-align:left; min-width:120px;">版本号</th>
                                    <th style="padding:0.75rem; text-align:left; min-width:200px;">标题</th>
                                    <th style="padding:0.75rem; text-align:left; min-width:100px;">类型</th>
                                    <th style="padding:0.75rem; text-align:left; min-width:140px;">发布时间</th>
                                    <th style="padding:0.75rem; text-align:left; min-width:160px;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($versions as $v): ?>
                                    <tr style="border-bottom:1px solid #E2E8F0;">
                                        <td style="padding:0.75rem;"><?php echo htmlspecialchars($v['version_code']); ?></td>
                                        <td style="padding:0.75rem;"><?php echo htmlspecialchars($v['title']); ?></td>
                                        <td style="padding:0.75rem;">
                                            <span style="display:inline-block; padding:0.25rem 0.5rem; border-radius:0.25rem; 
                                                <?php echo $v['type'] == '功能' ? 'background:#EFF6FF;color:#1E40AF' : 
                                                      ($v['type'] == '优化' ? 'background:#ECFDF5;color:#065F46' : 
                                                      ($v['type'] == '修复' ? 'background:#FEF3C7;color:#92400E' : 
                                                      'background:#F3E8FF;color:#6B21A8')); ?>">
                                                <?php echo $v['type']; ?>
                                            </span>
                                        </td>
                                        <td style="padding:0.75rem;"><?php echo htmlspecialchars($v['create_time']); ?></td>
                                        <td style="padding:0.75rem;">
                                            <!-- 编辑按钮：点击显示表单并填充数据 -->
                                            <a href="javascript:;" class="btn btn-sm btn-outline" 
                                               onclick="showForm('编辑版本', <?php echo $v['id']; ?>, 
                                               '<?php echo htmlspecialchars($v['version_code']); ?>', 
                                               '<?php echo htmlspecialchars($v['title']); ?>', 
                                               '<?php echo htmlspecialchars($v['type']); ?>', 
                                               '<?php echo htmlspecialchars($v['content']); ?>')">
                                                编辑
                                            </a>
                                            <a href="version.php?delete=<?php echo $v['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('确定删除？')">删除</a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($versions)): ?>
                                    <tr>
                                        <td colspan="5" style="padding:2rem; text-align:center; color:#64748B;">暂无版本记录</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // 显示表单（新增/编辑通用）
        function showForm(title, id, versionCode = '', titleVal = '', typeVal = '', contentVal = '') {
            // 填充表单数据
            document.getElementById('formTitle').textContent = title;
            document.getElementById('formId').value = id;
            document.getElementById('version_code').value = versionCode || 'V';
            document.getElementById('title').value = titleVal;
            document.getElementById('type').value = typeVal || '功能';
            document.getElementById('content').value = contentVal;
            
            // 显示表单
            document.getElementById('versionFormCard').classList.remove('hidden');
        }

        // 隐藏表单
        function hideForm() {
            document.getElementById('versionFormCard').classList.add('hidden');
        }

        // 页面加载时，如果是编辑状态，自动显示表单（处理可能的错误回显）
        <?php if (!empty($currentVersion) || $error): ?>
            window.onload = function() {
                <?php if (!empty($currentVersion)): ?>
                    // 编辑状态：填充数据并显示
                    showForm('编辑版本', 
                        <?php echo $currentVersion['id']; ?>, 
                        '<?php echo htmlspecialchars($currentVersion['version_code']); ?>', 
                        '<?php echo htmlspecialchars($currentVersion['title']); ?>', 
                        '<?php echo htmlspecialchars($currentVersion['type']); ?>', 
                        '<?php echo htmlspecialchars($currentVersion['content']); ?>'
                    );
                <?php else: ?>
                    // 有错误时显示表单（保留用户输入）
                    document.getElementById('versionFormCard').classList.remove('hidden');
                <?php endif; ?>
            };
        <?php endif; ?>
    </script>
</body>
</html>